<?php 

$db=New Controller_hello();


// switch ($_GET['type']) {
// 	case '1':
		
// 		break;
// 	case '2':
		
// 		break;
// 	default:
// 		# code...
// 		break;
// }

var_dump($db->Test());

class Controller_hello
{

	public function Test(){

        $date=self::php_do_Url_GET(
           //'https://feiyu.oceanengine.com/crm/v2/openapi/pull-clues/'
            'https://ad.oceanengine.com/open_api/2/tools/clue/get/'
            ,['advertiser_ids'=>[1671616657392654],'start_time'=>'2020-07-01','end_time'=>'2020-07-10']
            ,["Access-Token:852a85cc100435e81af62b12d017576f33039e79"]
        );

        return $date;

		// $requestBody=json_decode(file_get_contents('json/data.json'),true);

		// echo '<pre>';

		// var_dump($requestBody);

		// echo '</pre>';


		// $site_id=$requestBody['site_id'];
		// $page_id=$requestBody['page_id'];
		// $name=$requestBody['data'][0]['value'];
		// $phone=$requestBody['data'][1]['value'];
		// $data_submit=date('Y-m-d H:i:s');
		// //$qudao='鼎盛原生2';
		// $city=self::selectCity($phone);

		// self::zi($name,$phone,$qudao,$city,'');

		// $qure="INSERT INTO badu_seoPhone (site_id,page_id,name,phone,date_submit,city,qudao) VALUE('{$site_id}','{$page_id}','{$name}','{$phone}','{$data_submit}','{$city}','{$qudao}');";
		// $host='localhost';
		// $user='root';
		// $password='root';
		// $database='weizandata';
		// $link=mysqli_connect($host, $user, $password, $database);
		// $link->query("set names utf8");

		// $result=mysqli_query($link, $qure);

		
		// if($result){

		// 	return 'success';

		// }else{

		// 	return '语句：'.$qure.'<br>错误代码: '.mysqli_errno($link).'<br> 错误解释: '.mysqli_error($link).'<br>';

		// }

		// mysqli_close($link);

	}
    public function feiyuget(){

        $request = new HttpRequest();
        $request->setUrl('https://feiyu.oceanengine.com/crm/v2/openapi/pull-clues/');
        $request->setMethod(HTTP_METH_GET);

        $request->setQueryData(array(
          'advertiser_ids' =>'[1671616657392654]',
          'start_time' =>'2020-01-1',
          'end_time' =>'2020-07-17'
        ));

        $request->setHeaders(array(
          'Content-Type' =>'application/json',
          'access_token' =>'852a85cc100435e81af62b12d017576f33039e79'
        ));

        try {

          $response = $request->send();

          echo $response->getBody();

        } catch (HttpException $ex) {

          echo $ex;

        }

    }
    public function getFeiYuData(){

          // 今日头条飞鱼CRM系统API域名
          $host = 'https://ad.oceanengine.com';

          // 拉取数据的路由
          $pull_route = '/crm/v2/openapi/pull-clues/';

          // 飞鱼CRM系统中,你生成的秘钥字符串,这里要替换成你自己的key
          $signature_key = 'RkFUSE1FN1BXNzdH';

          // 飞鱼CRM系统中,你生成的Token字符串,这里要替换成你自己的Token
          $token = '852a85cc100435e81af62b12d017576f33039e79';

          // 飞鱼的加密参数还有三个:start_time、end_time、timestamp,这三个字段都是时间戳格式

          // 拉取的数据从哪一天开始取数据,开始日期,例如从 2019-08-01 开始取数据
          $start_time = strtotime('2020-07-01');

          // 拉取的数据到哪一天截止停止取数据,结束日期,例如到 2019-09-01 停止取数据
          $end_time = strtotime('2020-07-31');

          // 时间戳,当前执行加密方法的时间
          $timestamp = time();

          // 飞鱼CRM担心数据量太大会挂掉,所以要求进行分页获取数据,这个是第几页
          $page = 1;

          // 每页数据要多少条,例如我设置每页获取10条数据
          $page_size = 10;

          // 以上必须得参数都提供完整无误后,就可以进行数据加密了

          // 第一步,将拉取数据的路由和开始日期和结束日期和时间戳进行拼接,结果类似这样:"/crm/v2/openapi/pull-clues/?start_time=1569859200&end_time=1572537600 1572574424"
          // 注意:这一步有一个空格,一定要保留,否则签名会失败的!!!
          // 注意:这一步有一个空格,一定要保留,否则签名会失败的!!!
          // 注意:这一步有一个空格,一定要保留,否则签名会失败的!!!
          $data = $pull_route.'?start_time='.$start_time.'&end_time='.$end_time.' '.$timestamp;

          // 第二步,将第一步拼接后的字符串进行哈希256加密,然后将结果再进行base64加密
          $signature = base64_encode(hash_hmac('sha256', $data, $signature_key));

          // 第三步,配置curl信息,然后获取数据,请求地址类似这样:"https://feiyu.oceanengine.com/crm/v2/openapi/pull-clues/?page=1&page_size=10&start_time=1569859200&end_time=1572537600"
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $host.$pull_route.'?page='.$page.'&page_size='.$page_size.'&start_time='.$start_time.'&end_time='.$end_time);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

          // 设置超时时间
          curl_setopt($ch, CURLOPT_TIMEOUT, 5);

          // 设置请求头信息,每个头信息的冒号后面要保留一个空格
          curl_setopt($ch, CURLOPT_HTTPHEADER, [
              'Content-Type: application/json;charset=UTF-8',
              'Signature: ' . $signature,
              'Timestamp: ' . $timestamp,
              'Access-Token: ' . $token,
          ]);

          // 执行curl获取数据
          $output = curl_exec($ch);

          // 关闭资源
          curl_close($ch);

          // 如果不出意外,那么这里你就可以获取到飞鱼CRM系统中的客户信息了
          //print_r($output);

          return $output;



    }

	private function selectCity($phone){


			$phoneD=substr($phone,0,7);
			$qure="SELECT CONCAT(province,city) AS city FROM phone WHERE phone='{$phoneD}';";
			$host='localhost';
			$user='root';
			$password='root';
			$database='phone';
			$link=mysqli_connect($host, $user, $password, $database);
			$link->query("set names utf8");

			$result=mysqli_query($link, $qure);
			$arr=mysqli_fetch_all($result, 1);
			mysqli_close($link);
			return $arr[0]['city'];


	}

    private function do_curl($url, $params = array(), $upload = false, $type = 'POST')
    {
        
        $token = file_get_contents("tt/token.txt");

        if(!$token){
            self::gettoken();
            $token = file_get_contents("tt/token.txt");
        }

        $method = strtoupper($type);
        if ($method == 'GET') {
            $url = "{$url}?" . http_build_query($params);
        }
        $ch = curl_init();
        //curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        //输出主机头
        if ($url=="https://capi.qumei.com/api/home/call"){
            //定义请求类型
            $username="webuser";
            $password="Qumei1993";
            $timestamp=time();

            $sign = md5($username.",".$password.",".$timestamp);

            $headers = array(
                "Content-Type: application/json",
                "Authorization: Bearer $token",
                "username: $username",
                "password: $password",
                "timestamp: $timestamp",
                "sign: $sign"
            );

            // foreach ($headers as $v){
            //    // echo $v."\r\n";
            // }

            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        // 是否检测服务器的证书是否由正规浏览器认证过的授权CA颁发的
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 是否检测服务器的域名与证书上的是否一致
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        if ($method == 'POST') {
            if ($upload) {        //设置上传文件
                $file = new \CURLFile($upload['tmp_name'], $upload['type'], $upload['name']);
                $params[$upload['get_name']] = $file;
            }
            //$params = '{"Service":"com.QM.CallCenter.CommonChannelAPI","Param":{\"CusName\":\"test591\u5ba2\u8d44\uff08\u8bf7\u5ffd\u7565\uff09\",\"CusPhone\":\"15107984564\",\"ChannelID\":\"1262592253055078400\",\"CusAddress\":\"\u5317\u4eac\",\"Remark\":\"\"}}';
            @curl_setopt($ch, CURLOPT_POST, 1);
            @curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        $result = curl_exec($ch);
        //$request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        //print_r($request_header);
        //打印发送头信息
        curl_close($ch);
        if ($result === null || $result === false) {
            $this->error('操作出错！');
        } else {
            return $result;
        }
    }

    private function gettoken()
    {
        $data = array();
        $data['grant_type']="password";
        $data['username']="webuser";
        $data['password']="Qumei1993";
        $out = self::do_curl("https://capi.qumei.com/token",$data,"","POST");
        $out = json_decode($out,true);
        file_put_contents("tt/token.txt",$out["access_token"]);
    //var_dump($out["access_token"]);
    }  


    public function zi($CusName,$CusPhone,$ChannelID,$CusAddress,$Remark='')
    {

            $data["CusName"]= $CusName;
            $data["CusPhone"]= $CusPhone;
            $data["ChannelID"]= $ChannelID;
            $data["CusAddress"]= $CusAddress;
            $data["Remark"]= $Remark;
            $data = json_encode($data);
            $pp["Service"] = "com.QM.CallCenter.CommonChannelAPI";
            $pp["Param"] = addslashes($data);

            $pp = json_encode($pp);
            $pp = str_replace('\\\\\\',"\\",$pp);

            $out = self::do_curl("https://capi.qumei.com/api/home/call",$pp,false,"POST");
            $out = json_decode($out,true);

            if ($out['statusCode']==200){

                 return '提交成功';

            }else{

                 return '提交失败';

            }

    }

    public function  php_do_url_POST($url,$params,$headers){ //POST get

        $ch = curl_init ();

        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $json_string = curl_exec ( $ch );
        $data = json_decode($json_string, true);
        curl_close ( $ch );
        return $data;
    }
    public function php_do_Url_GET($url,$params,$headers){ //Get get

        $url = "{$url}?" . http_build_query ($params);
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);    

        $json_string = curl_exec ( $ch );

        $data = json_decode($json_string, true);

        curl_close ( $ch );

        return $data;
    }


}



 ?>